//
//  AuthenCompanyMercPhotoVM.swift
//  kxf
//
//  Created by Mac on 2024/3/8.
//

import Foundation
import UIKit
import MCToast

class AuthenCompanyMercPhotoVM: UIView {
    
    var selfHeight = AuthenPhotoLargeVM().selfHeight+RegisterViewHeadTitleVM().selfHeight
    var controller = WHBaseViewVC()
    
    var licenceOcrBlock:((NSDictionary)->())?
    
    override init(frame:CGRect){
        super.init(frame: CGRect.init(x: 0, y: frame.origin.y, width: SCREEN_WIDHT, height: selfHeight))
        self.selfHeight = frame.size.height
        self.backgroundColor = .white
        self.isUserInteractionEnabled = true
        
        initUI()
    }
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    lazy var photoTitleVm : RegisterViewHeadTitleVM = {
        let vm = RegisterViewHeadTitleVM.init(frame: CGRect.init(x: 0, y: 0, width: 0, height: 0))
        vm.titleLabel.text = "营业执照"
        return vm
    }()
    lazy var mercFrontPhotoVm : AuthenPhotoLargeVM = {
        let vm = AuthenPhotoLargeVM.init(frame: CGRect.init(x: 0, y: self.photoTitleVm.frame.maxY, width: 0, height: 0  ))
        vm.titleLabel.text = "点击上传营业执照"
        vm.addIconImg.setImgLocal(imgName: "authen_photo_id")
        vm.photoBlock = {()in
            self.takePickture()
        }
        vm.exampleBlock = {()in
            self.sampleAlertVm.showExampleImage(type: .licence)
        }
        return vm
    }()
    
    lazy var sampleAlertVm : AuthenPhotoSampleAlertVM = {
        let vm = AuthenPhotoSampleAlertVM.init(frame: .zero)
        vm.isHidden = true
        return vm
    }()
}

extension AuthenCompanyMercPhotoVM{
    func initUI() {
        addSubview(photoTitleVm)
        addSubview(mercFrontPhotoVm)
        UIApplication.shared.keyWindow?.addSubview(sampleAlertVm)
    }
    func updateUIForRefuse() {
        self.mercFrontPhotoVm.setImgUrl(urlstring: "\(AuthenCompanyMsgModel.shareInstance.photoImgUrlLicence)")
    }
    func setReadMode() {
        self.mercFrontPhotoVm.setReadMode()
    }
}


extension AuthenCompanyMercPhotoVM:UIImagePickerControllerDelegate,UINavigationControllerDelegate{
    @objc func takePickture(){
        let alertController=UIAlertController(title: "请选择照片来源", message: nil, preferredStyle: .actionSheet)

        let cancel=UIAlertAction(title:"取消", style: .cancel, handler: nil)
        
        let takingPictures=UIAlertAction(title:"拍照", style: .default){ action in
            if UIImagePickerController.isSourceTypeAvailable(.camera){
                let  cameraPicker = UIImagePickerController()
                cameraPicker.delegate = self
                cameraPicker.sourceType = .camera
//                cameraPicker.allowsEditing = true
                //在需要的地方present出来
                self.controller.present(cameraPicker, animated: true, completion: nil)
            } else {
                print("不支持拍照")
            }
        }
        let photoPictures=UIAlertAction(title:"相册", style: .default){ action in
            if UIImagePickerController.isSourceTypeAvailable(.photoLibrary){
                let  cameraPicker = UIImagePickerController()
                cameraPicker.delegate = self
                cameraPicker.allowsEditing = true
                cameraPicker.sourceType = .photoLibrary
                //在需要的地方present出来
                self.controller.present(cameraPicker, animated: true, completion: nil)
            } else {
                print("不支持拍照")
            }
        }
        
        alertController.addAction(cancel)
        alertController.addAction(takingPictures)
        alertController.addAction(photoPictures)
        
        self.controller.present(alertController, animated:true, completion:nil)
    }
    func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) {
        print("获得照片============= \(info)")
        self.controller.dismiss(animated: true, completion: nil)
        
        MCToast.mc_loading()
        let image = (info[UIImagePickerController.InfoKey.originalImage] as? UIImage)!
        let imageData = WHRequestTools.compressImage(toData: image)
//        let imageData = image.jpegData(compressionQuality: 1.0)
        
        DSImageUploader.shared.uploadImages(_image: imageData!,imgType:"idCardFront") { text, value in
            MCToast.mc_remove()
//            DLLog(message: "\()")
            if value == true{
                self.sendOcrIdCardRequest(urlString: "\(text)")
            }else{
                MCToast.mc_text("图片上传失败")
            }
        }
    }
}

extension AuthenCompanyMercPhotoVM{
    func sendOcrIdCardRequest(urlString:String) {
        MCToast.mc_loading()
        WHNetworkUtil.shareManager().GET(urlString: "\(URL_OCR_licenseReg)?url=\(urlString)", vc: self.controller) { responseObject in
            DLLog(message: "\(responseObject)")
            if responseObject["code"]as? Int ?? 0 == 200{
                self.mercFrontPhotoVm.setImgUrl(urlstring: "\(urlString)")
                AuthenCompanyMsgModel.shareInstance.photoImgUrlLicence = "\(urlString)"
                if self.licenceOcrBlock != nil{
                    self.licenceOcrBlock!(responseObject["data"]as? NSDictionary ?? [:])
                }
            }else{
                self.controller.presentAlertVcNoAction(title: "\(responseObject["message"]as? String ?? "识别失败，请重新拍摄照片")", viewController: self.controller)
            }
            
        }
    }
}
